import {
  createDevice,
  deleteDevice,
  getDeviceListByCode,
  getDeviceTypeList,
  updateDevice
} from '@/api'
import { useConfig } from '@/composables/useConfig'
import type { DeviceData, DeviceType } from '@/views/Config/types'
import { ElButton, ElInput, ElOption, ElSelect, ElSwitch } from 'element-plus'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useCarStore } from './car'
import { ElMessage } from './elMessage'

export const useConfigDeviceStore = defineStore('config-device', () => {
  const { t } = useI18n()
  const {
    handleVisible,
    loading,
    tableData,
    closeLoading,
    openLoading,
    handleCancel,
    handleEdit,
    formData,
    formVisible,
    setForm
  } = useConfig()
  const carStore = useCarStore()

  const columns = computed(() => [
    {
      label: t('che-liang-bian-hao'),
      prop: 'rid'
    },
    {
      label: t('wai-she-ming-cheng'),
      prop: 'name'
    },
    {
      label: t('wai-she-lei-xing'),
      prop: 'type'
    },
    // {
    //   label: t('wai-she-zhuang-tai'),
    //   prop: 'status',
    //   slot: (row: DeviceData) => {
    //     if (row.status === '0') {
    //       return t('guan-bi')
    //     } else if (row.status === '1') {
    //       return t('kai-qi')
    //     } else {
    //       return ''
    //     }
    //   }
    // },
    {
      label: t('cao-zuo'),
      slot: (row: DeviceData) => (
        <div>
          <ElButton link loading={loading.value} onClick={() => handleDelete(row.id)}>
            {t('shan-chu')}
          </ElButton>
          <ElButton link onClick={() => handleEdit<DeviceData>(row)}>
            {t('bian-ji')}
          </ElButton>
        </div>
      )
    }
  ])

  const formRules = {
    rid: [{ required: false, message: t('che-liang-bian-hao') }],
    name: [{ required: true, message: t('wai-she-ming-cheng') }],
    type: [{ required: true, message: t('wai-she-lei-xing') }],
    intranatPort: [{ required: true, message: t('nei-wang-duan-kou') }],
    intranatIp: [{ required: true, message: t('nei-wang-ip') }],
    internatPort: [{ required: true, message: t('wai-wang-duan-kou') }],
    internatIp: [{ required: true, message: t('wai-wang-ip') }]
  }

  const deviceTypeList = ref<DeviceType[]>([])

  const formFields = computed(() => [
    {
      prop: 'rid',
      title: t('che-liang-bian-hao'),
      slot: () => <ElInput v-model={carStore.currentCar}></ElInput>
    },
    {
      prop: 'name',
      title: t('wai-she-ming-cheng')
    },
    {
      prop: 'type',
      title: t('wai-she-lei-xing'),
      slot: (form: DeviceData) => (
        <ElSelect
          class="w-full"
          modelValue={form['type']}
          placeholder={t('wai-she-lei-xing')}
          clearable
          onChange={(val: any) => setForm(val, 'type')}
        >
          {deviceTypeList.value.map((item: DeviceType) => (
            <ElOption key={item.id} label={item.name} value={item.type}></ElOption>
          ))}
        </ElSelect>
      )
    },
    {
      prop: 'status',
      title: t('wai-she-zhuang-tai-0'),
      slot: (form: DeviceData) => (
        <ElSwitch
          class="my-2"
          modelValue={form['status']}
          active-text={t('kai-qi')}
          inactive-text={t('guan-bi')}
          style="--el-switch-off-color: #808080"
          active-value={'1'}
          inactive-value={'0'}
          onChange={(val: any) => setForm(val, 'status')}
        />
      )
    },
    {
      prop: 'intranatPort',
      title: t('nei-wang-duan-kou')
    },
    {
      prop: 'intranatIp',
      title: t('nei-wang-ip')
    },
    {
      prop: 'internatPort',
      title: t('wai-wang-duan-kou')
    },
    {
      prop: 'internatIp',
      title: t('wai-wang-ip')
    }
  ])

  function setDeviceTypeList(data: DeviceType[]) {
    deviceTypeList.value = data
  }

  async function getList() {
    const res = await getDeviceListByCode(carStore.currentCar, 'patroling')
    const data = res.data || []
    tableData.value = data
    const r = await getDeviceTypeList()
    setDeviceTypeList(r.data || [])
  }

  async function handleDelete(id: number) {
    openLoading()
    try {
      const res: any = await deleteDevice(id)
      ElMessage({ type: 'success', message: res.message })
    } finally {
      closeLoading()
    }
    getList()
  }

  async function handleSubmit() {
    openLoading()
    try {
      let res: any
      const data = { ...formData.value }
      if (data.id) {
        data.status = Number(data.status)
        res = await updateDevice(data)
      } else {
        data.isDel = 0
        data.rid = carStore.currentCar
        data.rtype = 'patroling'
        data.status = Number(data.status)
        res = await createDevice(data)
      }
      ElMessage({ type: 'success', message: res.message })
      handleCancel()
    } finally {
      closeLoading()
      getList()
    }
  }

  return {
    columns,
    handleVisible,
    formRules,
    formFields,
    setDeviceTypeList,
    tableData,
    getList,
    handleDelete,
    handleCancel,
    handleSubmit,
    formVisible,
    formData,
    setForm,
    loading
  }
})
